package com.geek.novel.services.manager

import android.os.Bundle
import android.os.Message
import android.text.TextUtils
import com.geek.novel.common.BookDownloadEnum
import com.geek.novel.common.Constant
import com.geek.novel.entity.BookDownload
import com.geek.novel.entity.BookIndex
import com.geek.novel.event.EventHandler
import com.geek.novel.services.BookDownloadRepository
import com.geek.novel.services.BookRepository
import com.geek.novel.services.CrawlerRepository
import com.geek.novel.utils.LogCatUtil
import com.geek.novel.vo.CrawlerSectionVo

/**下载书籍的线程处理*/
open class BookDownloadThread(private val bookDownload: BookDownload, private val handler: EventHandler): EventHandler, Runnable{

    /**小说接口*/
    private val bookRepository = BookRepository.getInstance()

    /**小说爬取接口*/
    private val crawlerRepository = CrawlerRepository.getInstance()

    /**书籍缓存的数据库服务类*/
    private val bookDownloadRepository = BookDownloadRepository.getInstance()

    /**章节目录数量*/
    private var bookIndexSize = 0

    /**是否停止线程*/
    private var stop = false
    open fun stop(){
        this.stop = true
    }
    open fun isStop(): Boolean{
        return stop
    }

    override fun run() {
        LogCatUtil.i("???", "开始下载书籍缓存")
        this.sendMessageString("开始缓存")

        if(TextUtils.isEmpty(bookDownload.bookId)){
            this.handleError("缓存书籍id不能为空！请删除任务后重试！")
            return
        }

        //获取书籍对象
        val book = bookRepository.findBookByBookId(bookDownload.bookId)
        if(book == null){
            this.handleError("获取书籍信息为空！请删除任务后重试！")
            return
        }

        //保存当时传进来的书籍爬虫信息
        book.bookCrawlerId = bookDownload.bookCrawlerId

        //获取章节列表
        val list = crawlerRepository.startCrawlerBook(book, this, false)
        if(list.isEmpty()){
            this.handleError("获取章节列表为空！请删除任务后重试！")
            return
        }
        var bookIndex: BookIndex? = null
        val start = bookDownload.crawlerIndex
        //遍历章节列表开始缓存数据
        bookIndexSize = list.size
        for(i in start until bookIndexSize){
            bookIndex = list[i]

            //判断是否暂停
//            val download = bookDownloadRepository.findByBookId(bookDownload.bookId) ?: break
//            if(download.status == BookDownloadEnum.PAUSE.typeCode){
            if(this.isStop()){
                LogCatUtil.i("???", "已暂停")
                this.sendMessageString("已暂停")
                return
            }

            //显示当前爬取的数据
            val msg = "缓存中($i/${bookIndexSize})：${bookIndex.indexName}"
            this.sendMessageString(msg)

            bookDownload.crawlerIndex = i
            bookDownloadRepository.save(bookDownload)

            //更新章节名到页面上
            val crawler = bookIndex.crawler
            if(crawler != null && crawler){//已经爬取过了
                Thread.sleep(100)
                continue
            }

            LogCatUtil.i("???", "开始缓存数据(${book.bookName})：${bookIndex.indexName}")
            crawlerRepository.startCrawlerBookSection(book, bookIndex, this)
        }

        //标记爬取完成
        bookDownload.status = BookDownloadEnum.FINISH.typeCode
        bookDownloadRepository.save(bookDownload)
        val msg = if(bookIndex != null){
            "缓存完成：${bookIndex.indexName}"
        }else{
            "缓存完成：缓存章节为空，请重试！"
        }
        this.sendMessageString(msg)

        //通知下载完成
        handler.sendHandlerMessage(Constant.handler_event_book_download_update_success, bookDownload)

    }

    /**发送消息更新页面*/
    private fun sendMessageString(msg: String){
        handleSendMessage(Constant.handler_event_book_download_update_message, msg)
    }
    /**发送消息更新页面*/
    private fun handleSendMessage(code: Int, msg: String, data: Bundle?=null){
        val bundle = data?:Bundle()
        bundle.putString("bookId", bookDownload.bookId)
        bundle.putLong("bookCrawlerId", bookDownload.bookCrawlerId)
        bundle.putString("message", msg)
        handler.sendHandlerMessage(code, bookDownload, bundle)
    }

    /**处理错误信息*/
    private fun handleError(msg: String){
        LogCatUtil.e("???", msg)
        this.handleSendMessage(Constant.handler_event_book_download_update_error_message, msg)
    }


    /**处理线程CrawlerRepository里面的消息，再做一次转发*/
    override fun handleMessage(msg: Message) {
        when(msg.what){
            //完成章节索引列表的加载的回调
            Constant.handler_event_load_book_index->{
                this.sendMessageString( "获取章节列表完成")
            }
            //完成章节索引列表的加载的回调
            Constant.handler_event_load_book_section_page->{
                val crawlerSectionVo = msg.obj as CrawlerSectionVo
                val bookIndex = crawlerSectionVo.bookIndex?:return
                val pageIndex = crawlerSectionVo.pageIndex
                this.sendMessageString( "缓存中(${bookIndex.indexNum}/${bookIndexSize})：${bookIndex.indexName}-${pageIndex+1}")
            }
        }
    }

}